<meta charset="UTF-8">
<div class="pd-10 system" id="device-type-wraper">
    <div style="padding: 5px 0">
        <i-button icon="md-add" @click="openAddDeviceTypeModal">添加设备类型</i-button>
    </div>
    <div>
        <i-table :columns="columns" :data="tableData" :loading="loading"></i-table>
    </div>

    <!-- 添加车辆类型 -->
    <Modal v-model="addDevTypeModal" width="520" class-name="vertical-center-modal">
        <p slot="header" style="color:#2D8CF0;text-align:center">
            <Icon type="md-add"></Icon>
            <span v-show="!isEdit">添加设备类型</span>
            <span v-show="isEdit">编辑设备类型</span>
        </p>
        <div>
            <Row>
                <i-col :span="3" :offset="1" style="height: 100%;text-align:right;line-height:32px;">
                    类型名称&nbsp;:&nbsp;
                </i-col>
                <i-col :span="7">
                    <i-input v-model.trim="devTypeInfo.typename"></i-input>
                </i-col>
                <i-col :span="3" :offset="2" style="height: 100%;text-align:right;line-height:32px;">
                    通信协议&nbsp;:&nbsp;
                </i-col>
                <i-col :span="7"  v-show="!isEdit">
                    <i-select v-model="deviceCode">
                        <i-option v-for="item in deviceTypeList" :value="item.value" :key="item.value">{{ item.label }}</i-option>
                    </i-select>
                </i-col>
                <i-col :span="7"  v-show="isEdit">
                    <i-input v-model.trim="devTypeInfo.typecode" :disabled="isEdit"></i-input>
                </i-col>
            </Row>
            <Row style="margin:10px 0;">
                <i-col :span="3" :offset="1" style="height: 100%;line-height:32px;">
                    功能列表&nbsp;:&nbsp;
                </i-col>
            </Row>
            <Row style="margin:10px 0;">
                    <i-col :span="20" :offset="4" style="height: 100%;line-height:32px;">
                        <checkbox-group v-model="functions">
                            <Checkbox label="audio">
                                <span>录音</span>
                            </Checkbox>
                            <Checkbox label="camera">
                                <span>摄像头</span>
                            </Checkbox>
                            <Checkbox label="chat">
                                <span>对讲功能</span>
                            </Checkbox>
                            <Checkbox label="bms">
                                <span>电池管理</span>
                            </Checkbox>
                            <Checkbox label="obd">
                                <span>OBD</span>
                            </Checkbox>
                            <Checkbox label="weight">
                                <span>称重</span>
                            </Checkbox>
                            <Checkbox label="watermeter">
                                <span>水表</span>
                            </Checkbox>
                            <Checkbox label="video">
                                <span>视频</span>
                            </Checkbox>
                            <Checkbox label="activesafety">
                                <span>主动安全</span>
                            </Checkbox>
                        </checkbox-group>
                    </i-col>
            </Row>
            <Row>
                    <i-col :span="3" :offset="1" style="height: 100%;text-align:right;line-height:32px;">
                        备注&nbsp;:&nbsp;
                    </i-col>
                    <i-col :span="19">
                        <i-input v-model.trim="remark" :autosize="{minRows: 15}" type="textarea"></i-input>
                    </i-col>
            </Row>
        </div>
        <div slot="footer">
            <i-button type="primary" @click="handleAddDevType" style="width: 100%">{{isEdit?'编辑':'添加'}}</i-button>
        </div>
    </Modal>

    <Modal v-model="cmdModal" width="600" class-name="vertical-center-modal" fullscreen="false">
        <p slot="header" style="color:#f60;text-align:center">
            <Icon type="information-circled"></Icon>
            <span>选择设备指令</span>
        </p>
        <div>
            <Row style="margin: 10px 0" v-for="(item,index) in cmdList" :key="index">
                <i-col span="8" v-for="(type , index) in item" :key="type.cmdcode">
                    <Checkbox  v-model="checkboxCmdObj[type.cmdcode]" >{{type.cmdname}}</Checkbox>
                </i-col>
            </Row>
        </div>
        <div slot="footer">
            <i-button type="primary"  @click="addInstructionsToDeviceTypes" style="width: 100%">确定</i-button>
        </div>
    </Modal>

    <script>
        new Vue({
            el: "#device-type-wraper",
            data: function () {
                var me = this;
                return {
                    devTypeInfo: {
                        "typecode": null,
                        "typename": null,
                    },
                    functions:[],
                    remark:"",
                    deviceTypeList:[],
                    deviceCode:"",
                    isEdit: false,
                    addDevTypeModal: false,
                    cmdModal:false,
                    rowIndex: null,
                    oldtypename:null,
                    columns: [
                      
                        {
                            title: '类型名称',
                            key: 'typename'
                        },
                        {
                            title: '通信协议',
                            key: 'typecode'
                        },
                        {
                            title: '备注',
                            key: 'remark'
                        },
                        {
                            title: '操作',
                            key: 'action',
                            width: 250,
                            render: function (h, params) {
                                return h('div', [
                                    h('Button', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            marginRight: '5px'
                                        },
                                        on: {
                                            click: function () {
                                                me.openEditDevTypeModal(params);
                                            }
                                        }
                                    }, '修改'),
                                    h('Poptip', {
                                        props: {
                                            confirm: true,
                                            title: '确定要删除吗?'
                                        },
                                        on: {
                                            'on-ok': function () {
                                                me.handleDel(params);
                                            }
                                        }
                                    },[
                                    h('Button', {
                                            props: {
                                            type: 'error',
                                            size: 'small'
                                            }
                                        },"删除") 
                                    ]) 
                                ]);
                            }
                        }
                    ],
                    tableData: [],
                    cmdList:[],
                    checkboxCmdObj:{},
                    loading: false,
                    cmdRecords:[],
                }
            },
            methods: {
                openAddDeviceTypeModal: function () {
                    this.isEdit = false;
                    this.addDevTypeModal = true;
                },
                handleDel: function (params) {
                    var me = this;
                    var url = myUrls.deleteDeviceType();
                    var data = { devicetypeid: params.row.devicetypeid };
                    utils.sendAjax(url, data, function (resp) {
                        if (resp.status == 0) {
                            me.$delete(me.tableData, params.index);
                            me.delDevTypeModal = false;
                            me.$Message.success("删除成功");
                        } else {
                            me.$Message.success("删除失败");
                        };
                    });
                },
                handleAddDevType: function () {
                    var me = this;
                    var url = null;
                    var data = null;
                    var lock = true;
                    if (this.isEdit) {
                        url = myUrls.editDeviceType();
                        data = {
                            "devicetypeid": this.devTypeInfo.devicetypeid,
                            "typecode": this.devTypeInfo.typecode,
                            "newtypename": this.devTypeInfo.typename,
                            "oldtypename":this.oldtypename
                        }
                    } else {
                        url = myUrls.addDeviceType();
                        data = {
                            typecode: this.deviceCode,
                            typename: this.devTypeInfo.typename,
                        };
                    }
                    for(var key in data){
                        if(data.hasOwnProperty(key)){
                            if(!data[key]){
                                lock = false;
                            }
                        }
                    };
                    if(!lock){
                        this.$Message.error("参数都是必填的");
                        return;
                    }
                    if( this.functions && this.functions.length){
                        data.functions = this.functions.join(",");
                    }
                    if(this.remark !== ""){
                        data.remark = this.remark;
                    }
                    utils.sendAjax(url, data, function (resp) {
                        if (resp.status == 0) {
                            if (me.isEdit) {
                                for (var key in me.devTypeInfo) {
                                    if (me.devTypeInfo.hasOwnProperty(key)) {
                                        var val = me.devTypeInfo[key];
                                        me.tableData[me.rowIndex][key] = val;
                                    };
                                };
                                me.tableData[me.rowIndex].remark = me.remark;
                                me.$Message.success("编辑成功");
                            } else {
                                me.$Message.success("添加成功");
                                me.queryDevTypeList();
                            };
                            me.addDevTypeModal = false;
                        } else {
                            if (me.isEdit) {
                                if (resp.status == 1){  
                                    me.$Message.error("原设备类型不存在");
                                }else if (resp.status == 2){
                                    me.$Message.error("新的设备类型重复");
                                }
                            }else{
                                me.$Message.error("操作失败");
                            };   
                        }

                    })
                },
                openEditDevTypeModal: function (params) {
                    this.isEdit = true;
                    this.addDevTypeModal = true;
                    console.log('params', params);
                    this.oldtypename = params.row.typename;
                    params.row.functions ? this.functions = params.row.functions.split(","): this.functions = [];
                    this.remark = params.row.remark;
                    this.devTypeInfo = JSON.parse(JSON.stringify(params.row));
                    this.rowIndex = params.index;
                },
                addInstructionsToDeviceTypes:function(){
                    var url = myUrls.editDeviceTypeCmd();
                    var data = this.getEditDeviceTypeCmdData();
                    var me = this;
                    utils.sendAjax(url,data,function (resp) {
                        if(resp.status == 0){
                            me.$Message.success("设置成功");
                            me.cmdModal = false;
                            me.tableData[me.rowIndex].cmds = data.datas[0].cmds;
                            me.tableData[me.rowIndex].directiveCount = data.datas[0].cmds.length;
                        }else{
                            me.$Message.error(resp.cause);
                        }
                    })
                    
                },
                getEditDeviceTypeCmdData:function(){
                    var cmdList = this.cmdList;
                    var selectedCmdObj = this.checkboxCmdObj;
                    var cmds = [];
                        for(var key in selectedCmdObj){
                            if(selectedCmdObj.hasOwnProperty(key) && selectedCmdObj[key]){
                                cmdList.forEach(function (children) { 
                                    children.forEach(function (item) { 
                                        if(item.cmdcode == key){
                                            cmds.push(item);
                                        };
                                    })
                                })
                            };
                        };
                    return {datas:[{devicetype:this.tableData[this.rowIndex].devicetypeid,cmds: cmds}]}
                },
                queryDevTypeList: function () {
                    var me = this;
                    var url = myUrls.queryDeviceTypeByUser();
                    utils.sendAjax(url, {}, function (resp) {
                        if (resp.status == 0) {
                            resp.devicetypes.forEach(function (item) {
                                if(item.cmds){
                                    item.directiveCount = item.cmds.length;
                                }else{
                                    item.directiveCount = 0;
                                }       
                            })
                            
                            me.tableData = resp.devicetypes;
                            
                        }
                    })
                },
                matchingCmd:function(deviceType){
                    var me = this;
                    var index = 0;
                    me.checkboxCmdObj = {};
                    me.cmdList = [];
                    this.cmdRecords.forEach(function (item){ 
                        if(item.devicetype == deviceType){
                            var idx = parseFloat(index/3) 
                            if(index%3 == 0){
                                var newArr = [];
                                newArr.push(item)
                                me.cmdList.push(newArr);
                            }else{
                                me.cmdList[me.cmdList.length - 1].push(item);
                            }
                            me.checkboxCmdObj[item.cmdcode] = false;
                            index++;
                        }
                     });
                },
                querySelectedCmd:function () {
                    var url = myUrls.queryDeviceTypeHadCmd();
                    var data = {"devicetype":  this.tableData[this.rowIndex].devicetypeid};
                    utils.sendAjax(url,data,this.doQuerySelectedCmdFn);
                },
                doQuerySelectedCmdFn:function (resp) { 
                    var me = this;
                    if(resp.status == 0) {
                        this.tableData[me.rowIndex].cmds =  resp.records;
                        for(var key in me.checkboxCmdObj){
                            if(me.checkboxCmdObj.hasOwnProperty(key)){
                                me.checkboxCmdObj[key] = false;
                            }
                        };

                        resp.records.forEach(function (item){ 
                            me.checkboxCmdObj[item.cmdcode] = true;
                        });   
                        
                        this.tableData = JSON.parse(JSON.stringify(this.tableData));                      
                    }
                },
                queryCmdList: function () {
                    var me = this;
                    var url = myUrls.queryCmd();
                    var data = {
                        "offset": 0,
                        "pagesize": 100
                    };
                    utils.sendAjax(url, data, function (resp) {
                        if (resp.status === 0) {
                            var records = resp.records;
                            me.cmdRecords = records;
                        };
                    });

                },
                queryDeviceTypeCode:function(){
                    var me = this;
                    var url = myUrls.listDeviceTypeCode();
                    utils.sendAjax(url, {}, function (resp) {
                        if (resp.status === 0) {
                          console.log('resp', resp);
                          resp.types.forEach(function (item) { 
                              me.deviceTypeList.push({
                                  label:item,
                                  value:item
                              });
                          });      
                        }
                    });
                }
            },
            watch: {
                addDevTypeModal: function () {
                    if (!this.isEdit) {
                        this.devTypeInfo = {
                            "port": 0, "typecode": null,
                            "typename": null, "enable": 1,
                            "level": 0, "camera": 0,
                            "lcd": 0, "led": 0,
                            "phone": null, "tcpport": 0,
                            "udpport": 0,
                        }
                        this.remark = "";
                        this.functions = [];
                    }
                }
            },
            mounted: function () {
                this.queryDevTypeList();
                this.queryCmdList();
                this.queryDeviceTypeCode();
            }
        })
    </script>
</div>